# -*- coding: utf-8 -*-

import MySQLdb
import datetime,time,calendar

import logging,os

CURRECID_INDEX = 8 # sch表中currecid的次序，随表的变化而动态变化
log_file_name = 'log_file.txt'

logging.basicConfig(filename = os.path.join(os.getcwd(), log_file_name), \
    level = logging.INFO, filemode = 'a', \
    format = '%(asctime)s - %(levelname)s: %(message)s')
    
def sleep_time(hour,minute,second):
    return hour*3600+minute*60+second

def YYTimeToDateTime(strdate):
    #输入的strdate格式为:2016-11-30-09:45
    try:
        items = strdate.split('-')
        timeitems = items[-1].split(':')
        yytime = datetime.datetime(int(items[0]),int(items[1]),int(items[2]),int(timeitems[0]),int(timeitems[1]))
        return yytime
    except:
        return None

def update_db():
    conn = MySQLdb.connect(host='localhost',port = 3306, \
       user='root', passwd='123456',db ='mynjudb')
    cur = conn.cursor()

    ss = cur.execute("select * from sch where isboot=1 or currecid!=-1")
    logging.debug('number of isboot=1 or currecid!=-1: '+str(ss))

    curday = datetime.datetime.now()

    schs = cur.fetchmany(ss)
    for item in schs:
        currecid_i = CURRECID_INDEX
        
        str_currecid = str(item[currecid_i])
        hrs = cur.execute("select * from his_rec where id="+str_currecid)

        hisrecs = cur.fetchmany(hrs)
        for elem in hisrecs:
            consult_time = YYTimeToDateTime(elem[6])

            time_delta = curday-consult_time

            if time_delta.days>=0 and time_delta.seconds>3600:
                cur.execute('update his_rec set status="2" where id='+str_currecid)
                logging.info('update his_rec set status="2" where id='+str_currecid)

                stu_n = cur.execute("select * from stu where currecid="+str_currecid)

                stus = cur.fetchmany(stu_n)
                for stu in stus:
                    cur.execute('update stu set currecid=-1 where currecid='+str_currecid)
                    logging.info('update stu set currecid=-1 where currecid='+str_currecid)

                cur.execute('update sch set isboot=0 where currecid='+str_currecid)
                logging.info('update sch set isboot=0 where currecid='+str_currecid)
                cur.execute('update sch set currecid=-1 where currecid='+str_currecid)
                logging.info('update sch set currecid=-1 where currecid='+str_currecid)
                logging.info('\n')

    cur.close()
    conn.commit()
    conn.close()
    
if __name__ == '__main__':
    try:
        while True:
            update_db()
            time.sleep(sleep_time(24,0,0))
    except Exception as e:
        logging.error(str(e))
        pass
        
